package com.thinkgem.jeesite.modules.sys.interceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.thinkgem.jeesite.common.pojo.runtime.StringUtils;
import com.thinkgem.jeesite.common.web.cookie.CookieUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * Session超时拦截器
 * 
 * 包括登录信息
 */
public class SessionTimeoutInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = Logger.getLogger(SessionTimeoutInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		try {
			String uri = getURI(request);
			System.out.println("[SessionTimeoutInterceptor.preHandle] uri:" + uri);
			// 不在验证的范围内
			if(exclude(uri)) {
				return true;
			}
			//User user = UserUtils.getUser(request);
			User user = UserUtils.getUser();
			
			// 用户为null跳转到登陆页面
			//if (user == null || user.isNull()) {
			if (user == null) {
				String login = getLoginUrl(request);
				String diskid = CookieUtils.getCookie(request, "diskid");
				if (request.getHeader("x-requested-with") != null
	                     && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"))//如果是ajax请求响应头会有，x-requested-with；  
	             {  
				     CookieUtils.setCookie(response, "diskid", diskid);
					 String ctx = request.getContextPath();
					 ctx = ctx.substring(ctx.indexOf("/")+1);
					 CookieUtils.setCookie(response, "ctx", ctx);
	                 response.setStatus(403);
	                 return false;  
	             }else{
	                 response.sendRedirect(login+"?diskid="+diskid);
	 				 return false;
	             }
			}

			//System.out.println("[SessionTimeoutInterceptor.preHandle] requestUser=" + user.getString("job_no") + ";diskid=" + CookieUtils.getCookie(request, "diskid"));
			System.out.println("[SessionTimeoutInterceptor.preHandle] requestUser=" + user.getNo() + ";diskid=" + CookieUtils.getCookie(request, "diskid"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

	private String getLoginUrl(HttpServletRequest request) {
		StringBuilder buff = new StringBuilder();
		if (loginUrl.startsWith("/")) {
			String ctx = request.getContextPath();
			if (!StringUtils.isBlank(ctx)) {
				buff.append(ctx);
			}
		}
		buff.append(loginUrl).append("?");
		return buff.toString();
	}

	
	/**
	 * 获得第二个路径分隔符的位置
	 * 
	 * @param request
	 * @throws IllegalStateException
	 *             访问路径错误，没有三(四)个'/'
	 */
	private static String getURI(HttpServletRequest request)throws IllegalStateException {
		UrlPathHelper helper = new UrlPathHelper();
		String uri = helper.getOriginatingRequestUri(request);//请求路径
		System.out.println("[SessionTimeoutInterceptor.getURI] uri=" + uri);
		String ctxPath = helper.getOriginatingContextPath(request);//项目路径
		System.out.println("[SessionTimeoutInterceptor.getURI] ctxPath=" + ctxPath);
		int start = 0, end = 0, count = 0;
		//uri = uri.replace(ctxPath, "");  //将项目路径丛请求路径中移除
		start = uri.indexOf(ctxPath) + ctxPath.length();   //获得第一个分隔符的位置
		end = uri.indexOf('/', start + 1); //获得第二个分隔符的位置
		if (start < 0) {
			throw new IllegalStateException(uri);//如果请求中不包含分隔符则请求路径非法
		}
		if (end <=0){          
			end = uri.length();   //如果请求中只有一个分隔符则取从第一个分隔符到末尾
		}
		return uri.substring(start, end);
	}




	private boolean exclude(String uri) {
		if (excludeUrls != null) {
			for (String exc : excludeUrls) {
				if (exc.equals(uri)) {
					return true;
				}
			}
		}
		return false;
	}



	private String[] excludeUrls;
	private String loginUrl;


	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public void setExcludeUrls(String[] excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

}